<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handelDownload">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'descending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <image-holder :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              <!-- {{ scope.row.formOfEmployment }} -->
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable>
            <template v-slot="{ row }">
              <!-- {{ row }} -->
              {{ row.timeOfEntry | dateFormat }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="success" size="small" @click="$router.push('/detail?id='+row.id)">查看
              <!-- <el-button type="success" size="small" @click="$router.push(`/detail?id=${row.id}`)">查看 -->
              <!-- $router.push('/detail?id='+row.id)   查询参数的传参方式  不用改路由  使用$route.query.(问号后面的名称接受,)-->
              <!-- $router.push('/detail/row.id)   路由参数的传参方式 需要改路由 路由后面以 /:(自定义名称) 携带 使用$route.params.(自定义名字接收) -->
              <!-- 都可以在调试中查看 -->
              </el-button>
              <el-button type="primary" size="small" @click="hAssignRole(row.id) ">分配角色</el-button>
              <el-button type="danger" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <!-- 分页组件 -->
          <el-pagination
            :current-page="pageParams.page"
            :page-sizes="[2,3,5,10, 20, 30, 40]"
            :page-size="pageParams.pagesize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
          <el-pagination layout="prev,pager,next" />
        </el-row>
      </el-card>
    </div>
    <!-- 弹层 -->
    <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
      <addor-edit ref="aaa" @success="hSuccess" @close="showDialog=false" />
    </el-dialog>
    <!-- 角色弹层 -->
    <el-dialog
      :visible.sync="showDialogRole"
      title="分配角色"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <AssignRole ref="assignRole" :employee-id="curEmployeId" @close="showDialogRole=false" />
    </el-dialog>
  </div>
</template>
<script>
import PageTools from '@/components/PageTools'
import { getEmployeeList, delEmployee } from '@/api/employees'
import formEmployment from '@/constant/employees'
import addorEdit from './empDialog.vue'
import AssignRole from './assignRole'
// 一
// const hireType = {}
// formEmployment.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// 二
// const hireType = formEmployment.hireType.reduce((acc, item, index) => {
//   acc[item.id] = item.value
//   return acc
// }, {})
// 三
const hireType = formEmployment.hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
// console.log(hireType)
export default {
  components: {
    PageTools,
    'addor-edit': addorEdit,
    AssignRole
  },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      showDialogRole: false,
      showDialog: false,
      total: 0, // 所有信息条数
      list: [], // 员工信息
      pageParams: {
        page: 1, // 页码值
        pagesize: 10// 每页显示条数
      }
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 用户点击分配角色
    hAssignRole(id) {
      this.showDialogRole = true

      this.curEmployeId = id
      // console.log('父组件', this.curEmployeId)
      // this.$nextTick
      // 直接找到子组件，调用方法去获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
        // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    },
    // 导出
    async handelDownload() {
      try {
        const res = await getEmployeeList(this.pageParams.page, this.pageParams.pagesize)
        // console.log(res)
        if (res.code !== 10000) return
        // console.log(res.data.rows)
        const { headers, data } = this.formatData(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          excel.export_json_to_excel({
            header: headers,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
          this.downloadLoading = false
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 英文转中文
    formatData(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const one = list[0]
      let headers = []
      if (one) {
        headers = Object.keys(one).map((enkey) => {
          return mapInfo[enkey]
        })
      }
      const data = list.map(item => {
        const key = item['formOfEmployment'] // 1, 2
        item['formOfEmployment'] = hireType[key] // hireTypEnmu:{1:'正式', '2':'非正式' }
        return Object.values(item)
      })
      return { headers, data }
    },
    // 重置表单
    hClose() {
      this.$refs.aaa.resetForm()
    },
    // 关闭弹层
    hSuccess() {
      this.total++
      // 最后一页
      this.pageParams.page = Math.ceil(this.total / this.pageParams.pagesize)
      this.loadEmployeeList()
      this.showDialog = false
    },
    // 用户点击了删除
    hDel(id) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.doDel(id)
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        // console.log(res)
        // 1. 提示
        if (res.code !== 10000) return this.$message.error(res.message)
        this.$message.success('删除成功')
        // 2. 重新请求
        // 如果删除第最后一页（例如4）的最一条数据之后，页面会显示不正常
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        this.loadEmployeeList()
      } catch (err) {
        console.log('删除失败--->', err)
        this.$message.error('删除失败')
      }
    },

    formatEmployment(num) {
      // 从hireType中 通过id找到对应的元素的value
      // const item = formEmployment.hireType.find(its => its.id === num)
      // if (item) {
      //   return item.value
      // } else {
      //   return '不能确定'
      // }
      return hireType[num] || '未知'
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadEmployeeList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadEmployeeList()
    },
    // 获取员工列表
    async  loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams.page, this.pageParams.pagesize)
        // console.log(res)
        if (res.code !== 10000) return this.$message.error(res.message)
        this.total = res.data.total
        this.list = res.data.rows
        // this.$message.success(res.message)
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
